package service;

import JDBC.DBUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import method.ItemInformation;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
/**
 * @author Gao Shiwei
 * this class can show all items in the database
 */
@WebServlet(name = "AllItem")
public class AllItem extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
        resp.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, If-Modified-Since");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.addHeader("Access-Control-Allow-Credentials", "true");
        ItemInformation[] answer= DBUtils.QueryItemInformation();
        JsonObject Container=new JsonObject();

        JsonArray array=new JsonArray();

        JsonObject oneItem=new JsonObject();
        if(answer!=null) {
            for (int i = 0; i < answer.length; i++) {
                oneItem.addProperty("ItemID", answer[i].getItemID());
                oneItem.addProperty("ItemName", answer[i].getItemName());
                oneItem.addProperty("ItemPrice", answer[i].getItemPrice());
                oneItem.addProperty("ItemType", answer[i].getItemType());
                oneItem.addProperty("ItemDescription", answer[i].getItemDescription());
                oneItem.addProperty("ItemQuantity", answer[i].getItemQuantity());
                String picture = DBUtils.QueryItemPicture(answer[i].getItemID());
                if(picture!=null)
                    picture.replace("\\","\\\\");
                oneItem.addProperty("Picture", picture);
                oneItem.addProperty("CreateTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(answer[i].getCreateTime()));
                array.add(oneItem);
                oneItem=new JsonObject();
            }

            Container.add("Item", array);


            PrintWriter out = resp.getWriter();
            out.println(Container);
            out.flush();
            out.close();
        }else{
            Container.add("Item",null);
        }

    }
}
